<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>申请管理</el-breadcrumb-item>
      <el-breadcrumb-item>访客申请</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!--    功能区-->
        <div style="margin: 10px 0">
          <!--    搜索区-->
          <div style="margin: 10px 0">
            <el-input
              v-model="search"
              clearable
              placeholder="请输入标题"
              prefix-icon="Search"
              style="width: 20%"
            />
            <el-button
              icon="Search"
              style="margin-left: 5px"
              type="primary"
              @click="load"
            ></el-button>
            <el-button
              icon="refresh-left"
              style="margin-left: 10px"
              type="default"
              @click="reset"
            ></el-button>
            <div style="float: right">
              <el-tooltip content="添加" placement="top">
                <el-button
                  icon="plus"
                  style="width: 50px"
                  type="primary"
                  @click="add"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!--    表格-->
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          max-height="705"
          style="width: 100%"
        >
          <el-table-column label="#" type="index" />
          <el-table-column
            label="楼栋"
            prop="dormbuildName"
            width="100px"
            align="center"
          />
          <el-table-column
            label="宿舍号"
            prop="roomNum"
            width="100px"
            align="center"
          />
          <el-table-column
            label="学生姓名"
            prop="userName"
            width="100px"
            align="center"
          />
          <el-table-column
            label="来访人员姓名"
            prop="visitorName"
            width="100px"
            align="center"
          />
          <el-table-column
            :filter-method="filterTag"
            :filters="[
              { text: '男', value: '男' },
              { text: '女', value: '女' },
            ]"
            filter-placement="bottom-end"
            label="来访人员性别"
            prop="gender"
            width="100px"
            align="center"
          />
          <el-table-column
            label="来访人员手机号"
            prop="phoneNum"
            width="200px"
            align="center"
          />
          <el-table-column
            label="来源地"
            prop="originCity"
            sortable
            width="140px"
            align="center"
          />
          <el-table-column
            label="来访时间"
            prop="visitTime"
            sortable
            width="220px"
            align="center"
          />
          <el-table-column label="备注" prop="content" sortable />

          <el-table-column
            :filter-method="filterTag"
            :filters="[
              { text: '待审批', value: '待审批' },
              { text: '通过审批', value: '通过审批' },
              { text: '拒绝审批', value: '拒绝审批' },
            ]"
            filter-placement="bottom-end"
            label="申请状态"
            prop="state"
            sortable
            width="150px"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.state === '通过审批'
                    ? 'success'
                    : scope.row.state === '拒绝审批'
                    ? 'danger'
                    : 'info'
                "
                disable-transitions
                >{{ scope.row.state }}
              </el-tag>
            </template>
          </el-table-column>

          <!--      操作栏-->
          <el-table-column label="操作" width="130px">
            <template #default="scope">
              <el-button
                v-if="scope.row.state !== '通过审批'"
                icon="Edit"
                type="primary"
                @click="handleEdit(scope.row)"
              ></el-button>
              <el-popconfirm
                title="确认删除？"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button
                    v-if="scope.row.state === '待审批'"
                    icon="Delete"
                    type="danger"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="margin: 10px 0">
          <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <!--      弹窗-->
        <div>
          <el-dialog
            v-model="dialogVisible"
            title="操作"
            width="30%"
            @close="cancel"
          >
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="120px"
            >
              <el-form-item label="楼栋" prop="dormbuildName">
                <el-select
                  v-model="form.dormbuildName"
                  placeholder="请输入楼栋"
                  style="width: 80%"
                >
                  <el-option label="一号楼" value="一号楼" />
                  <el-option label="二号楼" value="二号楼" />
                  <el-option label="三号楼" value="三号楼" />
                  <el-option label="四号楼" value="四号楼" />
                </el-select>
                <!-- <el-input
                  v-model="form.dormBuildId"
                  style="width: 80%"
                ></el-input> -->
              </el-form-item>
              <el-form-item label="宿舍号" prop="roomNum">
                <el-input
                  v-model="form.roomNum"
                  clearable
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item label="学生姓名" prop="userName">
                <el-input
                  v-model="form.userName"
                  clearable
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="visitorName">
                <el-input
                  v-model="form.visitorName"
                  clearable
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio v-model="form.gender" label="男">男</el-radio>
                <el-radio v-model="form.gender" label="女">女</el-radio>
              </el-form-item>
              <el-form-item label="手机号" prop="phoneNum">
                <el-input
                  v-model="form.phoneNum"
                  clearable
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item label="来源地" prop="originCity">
                <el-input
                  v-model="form.originCity"
                  clearable
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item label="来访时间" prop="visitTime">
                <el-date-picker
                  v-model="form.visitTime"
                  clearable
                  placeholder="选择时间"
                  style="width: 48%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="来访信息" prop="content">
                <el-input
                  v-model="form.content"
                  :autosize="{ minRows: 3, maxRows: 10 }"
                  clearable
                  style="width: 80%"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script >
import request from "@/utils/request";

const { ElMessage } = require("element-plus");

export default {
  name: "VisitorInfo",
  components: {},
  data() {
    // 手机号验证
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      loading: true,
      disabled: false,
      judge: false,
      dialogVisible: false,
      search: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      detail: {},
      form: {},
      rules: {
        visitorName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            pattern: /^(?:[\u4E00-\u9FA5·]{2,10})$/,
            message: "必须由 2 到 10 个汉字组成",
            trigger: "blur",
          },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        phoneNum: [{ required: true, validator: checkPhone, trigger: "blur" }],
        visitTime: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入来访信息", trigger: "change" },
        ],
      },
    };
  },
  created() {
    const currentUser = JSON.parse(sessionStorage.getItem("user")); // 获取当前登录用户信息
    this.load();
    this.loading = true;
    setTimeout(() => {
      //设置延迟执行
      this.loading = false;
    }, 1000);
  },
  methods: {
    async load() {
      const currentUser = JSON.parse(sessionStorage.getItem("user")); // 获取当前登录用户信息
      console.log(currentUser);
      const name = currentUser.name; // 假设用户信息中包含 username
      request
        .get("/visitor/findByUsername", {
          params: {
            username: name, // 传递用户名参数
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        });
    },
    reset() {
      this.load();
    },
    filterTag(value, row) {
      return row.gender === value;
    },
    showDetail(row) {
      this.detailDialog = true;
      this.$nextTick(() => {
        this.detail = row;
      });
    },
    closeDetailDialog() {
      this.detailDialog = false;
    },
    add() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.disabled = false;
        this.form = {};
        const currentUser = JSON.parse(sessionStorage.getItem("user")); // 获取当前登录用户信息
        this.form.userName = currentUser.name;
        this.judge = false;
      });
    },
    save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.judge === false) {
            //新增
            await request.post("/visitor/add", this.form).then((res) => {
              console.log(res);
              if (res.code === "0") {
                ElMessage({
                  message: "新增成功",
                  type: "success",
                });
                this.search = "";
                this.load();
                this.dialogVisible = false;
              } else {
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          } else {
            //修改
            await request.put("/visitor/update", this.form).then((res) => {
              console.log(res);
              if (res.code === "0") {
                ElMessage({
                  message: "修改成功",
                  type: "success",
                });
                this.search = "";
                this.load();
                this.dialogVisible = false;
              } else {
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    handleEdit(row) {
      //修改
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        // 生拷贝
        this.form = JSON.parse(JSON.stringify(row));
        this.disabled = true;
      });
    },
    async handleDelete(id) {
      console.log(id);
      request.delete("/visitor/delete/" + id).then((res) => {
        if (res.code === "0") {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          this.search = "";
          this.load();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    handleSizeChange(pageSize) {
      //改变每页个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变页码
      this.currentPage = pageNum;
      this.load();
    },
  },
};
</script>